<!--
*@Author: QWP
*@Description: 发文拟稿、发文签批、发文归档
*@Params: pType  1/发文拟稿      2/发文签批     3/发文归档      4/公文套红 
*@Date: 2024-07-08 09:51:28
-->
<template>
  <a-layout class="f-h-100 s-bg-white">
    <u-table-header>
      <u-form
        :model="searchF.model"
        :gutter="16"
        :elements="searchEl"
        class="f-w-auto"
        :isSearch="true"
        @formChange="getSearch(1)">
        <a-col>
          <u-button-space>
            <u-icon-button @click="getSearch(1)">查询</u-icon-button>
            <u-icon-button
              itype="record"
              @click="showFlow = true"
              v-if="isReport != true">
              流程记录
            </u-icon-button>
          </u-button-space>
        </a-col>
        <a-col
          flex="1"
          align="end">
          <u-button-space>
            <template v-if="pType == 1">
              <u-icon-button
                itype="add"
                @click="toEdit(1)">
                新建发文
              </u-icon-button>
              <u-icon-button
                itype="edit"
                @click="toEdit(2)">
                修改
              </u-icon-button>
              <u-icon-button
                itype="report"
                @click="auditAbout('1')">
                上报
              </u-icon-button>
              <u-icon-button
                itype="recall"
                @click="auditAbout('4')">
                取回
              </u-icon-button>
              <u-icon-button
                itype="delete"
                @click="deleteBtn">
                删除
              </u-icon-button>
            </template>
            <template v-else-if="pType == 2">
              <u-icon-button
                itype="audit"
                @click="auditAbout('2')"
                v-if="showAuditBnt">
                审核
              </u-icon-button>
              <u-icon-button
                itype="recall"
                @click="auditAbout('4')"
                v-if="searchF.model.adstatus == '1'">
                取回
              </u-icon-button>
              <u-icon-button
                itype="close"
                @click="auditAbout('3')"
                v-if="showAuditBnt">
                退回
              </u-icon-button>
            </template>
            <template v-else-if="pType == 3">
              <u-icon-button
                itype="sort"
                @click="collectSort">
                归档
              </u-icon-button>
              <!-- <u-icon-button itype="export" @click="">导出</u-icon-button> -->
              <!-- <u-icon-button itype="print" @click="">批量打印</u-icon-button> -->
            </template>
            <template v-else-if="pType == '4'">
              <u-icon-button
                class="f-fr"
                @click="shhowRedEdit = true">
                公文套红
              </u-icon-button>
            </template>
          </u-button-space>
        </a-col>
      </u-form>
    </u-table-header>
    <u-table-content>
      <u-table
        :columns="columns"
        :data="tabData"
        v-model:pagination="pagenation"
        :loading="loading"
        :scroll="{ y: useTableScroll() }"
        @onSelect="({ selectedRows }) => (tabSelData = selectedRows)"
        @onDblclick="onDblclick"
        @change="getSearch"></u-table>
    </u-table-content>
  </a-layout>

  <!-- 编辑弹窗 -->
  <Edit
    v-model:open="showEdit"
    wrap-class-name="full-modal"
    :title="dialogTitle"
    :current="currntRow"
    :isCommon="isCommon"
    :isAudited="showAuditBnt"
    @success="
      showEdit = false;
      isCommon = false;
      currntRow = {};
      getSearch();
    "
    @close="currntRow = {}" />

  <!-- 套红编辑弹窗 -->
  <RedEdit
    v-model:open="shhowRedEdit"
    wrap-class-name="full-modal"
    title="公文套红" />

  <!-- 流程记录 -->
  <u-act-flowd
    v-model:open="showFlow"
    :selDatas="tabSelData"
    busiType="official_doc_dispatch" />
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, h, watch, onActivated } from "vue";
import { useRoute, useRouter, onBeforeRouteUpdate, onBeforeRouteLeave } from "vue-router";
import { useBaseStore, useLoginStore } from "@/store";
import { storeToRefs } from "pinia";
import { _IFormEl } from "@/components/common/form/interface";
import { ColProps, FormItemProps, TableColumnProps } from "ant-design-vue";
import dayjs from "dayjs";
import Edit from "./Edit.vue";
import RedEdit from "./RedEdit.vue";
import { cloneDeep } from "lodash";
import * as dispatchApi from "@/service/officialDoc/publishDoc/index.ts";
import { messageC, numberC, jsonCopy, alertC, nullC } from "@/util/common";
import { statusA } from "@/common/model/base";
import { useTableScroll } from "@/hooks/useTable";
import { useAuditAbout, IAuditParams } from "@/hooks/useAudit";
import { usePageTypeShow, useSearchShow } from "@/hooks/useAuditEl";
import { formatEmergency } from "@/views/oa/officialDoc/dispatch/emergencyTool.ts";

const props = defineProps<{
  isReport?: boolean;
}>();

const route = useRoute();
const { pType } = route.params;
const router = useRouter();
const { INC_NODE, EMERGENCY_DEGREE, OPEN_FORM, fileNoChars } = storeToRefs(useBaseStore());

onMounted(() => {
  initCols();
});

let pagenation = reactive({
  total: 0,
  current: 1,
  pageSize: 50,
  showTotal: (total) => `共 ${total} 条`,
});
const searchF = reactive({
  model: {
    createtime: "",
    keywords: "",
    docType: 1,
  },
});
const formItemProps: FormItemProps = {
  labelWidth: "72px",
  wrapperCol: { span: 24 },
  style: {
    width: "240px",
  },
};

// 曾经办，不显示审核和退回按钮
const showAuditBnt = ref<boolean>(useSearchShow(searchF.model, "1", { key: "adstatus", result: false, noResult: true }));

const searchEl: Array<_IFormEl> = reactive([
  {
    label: "审核状态",
    key: "status",
    element: "select",
    hide: pType != "1",
    formItemProps: formItemProps,
    componentProps: {
      options: statusA(1),
    },
  },
  {
    label: "审核状态",
    key: "adstatus",
    element: "select",
    hide: pType != "2",
    formItemProps: formItemProps,
    componentProps: {
      allowClear: false,
      options:
        pType == 1
          ? statusA(1)
          : [
              { label: "待审核", value: "0" },
              { label: "曾经办", value: "1" },
            ],
    },
  },
  { label: "拟稿日期", key: "createtime", element: "datepicker", formItemProps: formItemProps },
  {
    label: "紧急程度",
    key: "urgencyDegree",
    element: "select",
    formItemProps: formItemProps,
    hide: props.isReport != true,
    componentProps: { options: EMERGENCY_DEGREE.value },
  },
  {
    label: "关键字",
    key: "keywords",
    element: "input",
    formItemProps: { ...formItemProps, labelWidth: "50px" },
    componentProps: {
      placeholder: "发文标题、文件编号",
    },
  },
]);

// 列表
const loading = ref<boolean>(false);
const tabData = ref<any[]>([]);
const tabSelData = ref<any[]>([]);
let columns: Array<TableColumnProps> = reactive([
  { dataIndex: "index", title: "序号", width: 50, align: "center", customRender: ({ index }) => (index += 1) },
  { dataIndex: "title", title: "发文标题", width: 200 },
  // { dataIndex: "fileTitle", title: "文件标题", minWidth: 150 },
  {
    dataIndex: "incName",
    title: "文件编号",
    width: 160,
    customRender: ({ text, record }) => {
      const { fileNoChar, fileNoYear, fileNoOrder } = record;
      let noInfo = fileNoChars.value.find((i) => i.value == fileNoChar) || {};
      return `${nullC(noInfo["label"])}[${nullC(fileNoYear)}]${nullC(fileNoOrder)}`;
    },
  },
  { dataIndex: "urgencyDegree", title: "紧急程度", width: 150, align: "center", customRender: ({ text }) => formatEmergency(text) },
  { dataIndex: "username", title: "拟稿人", width: 150 },
  {
    dataIndex: "createtime",
    title: "拟稿日期",
    width: 150,
    customRender: ({ text }) => {
      return (text || "").split(" ")[0];
    },
  },
  // 不是报表页面才显示公文环节
  ...(props.isReport != true ? [{ dataIndex: "taskname", title: "公文环节", width: 150 }] : []),
  // 拟稿、签批、归档
  ...(["1", "2", "3"].includes(pType) ? [{ dataIndex: "reauditusername", title: "当前审核人", width: 150, align: "center" }] : []),
  // 归档
  ...(["3"].includes(pType)
    ? [{ dataIndex: "isFilter", title: "是否归档", width: 100, align: "center", customRender: ({ text }) => (text == "1" ? "是" : "否") }]
    : []),
]);

// 初始化列表表头
const initCols = (to?) => {
  let tTo = to ? to : route;
  const isAudit = {
    1: "0",
    2: "1",
    3: "2",
  };
  searchF.model.isAudit = isAudit[pType];

  if (searchF.model.isAudit == 1) {
    searchF.model.adstatus = "0";
  } else {
    searchF.model.adstatus = "";
  }

  searchF.model.status = pType == "1" ? "1" : "";

  // 报表 页面直接查询审核完成的数据
  if (props.isReport == true) {
    searchF.model.status = "3";
  }

  getSearch();
};

onActivated(() => {
  initCols(route);
});

// 列表查询
const getSearch = async (current?: number) => {
  loading.value = true;
  try {
    if (current == 1) {
      pagenation.current = 1;
    }
    searchF.current = pagenation.current;
    searchF.size = pagenation.pageSize;
    const res = await dispatchApi.page(searchF);
    if (res.code == 0) {
      tabData.value = res.data.records || [];
      pagenation.total = numberC(res.data.total || 0);
    }
  } catch (error) {}
  loading.value = false;
};

// 编辑
const currntRow = ref({});
let dialogTitle = ref<string>("新建发文");
let isCommon = ref<boolean>(false);
let showEdit = ref<boolean>(false);
let showFlow = ref<boolean>(false);
// type 1 新增     2 修改
const toEdit = (type: number, isCommon?: boolean): void => {
  if (type == 2) {
    if (tabSelData.value.length != 1) {
      alertC("请选择一条数据进行编辑!");
      return;
    }
    if (isCommon == true) {
      isCommon.value = true;
    }
    currntRow.value = tabSelData.value[0];
  }

  showEdit.value = true;
};

// 行双击
const onDblclick = (record) => {
  currntRow.value = record;
  showEdit.value = true;
};

// 套红编辑
let shhowRedEdit = ref<boolean>(false);

// 删除
const deleteBtn = (): void => {
  if (tabSelData.value.length == 0) {
    messageC("请先选择要删除的数据!", "warning");
    return;
  }

  let noDel = tabSelData.value.some((i) => ["2", "3"].includes(i["status"] + ""));
  if (noDel) {
    messageC("审核中或审核完成的数据不能删除!");
    return;
  }

  let ids = tabSelData.value.map((item) => item.keyid);
  alertC("确定删除选中的数据?", "confirm").then(async () => {
    try {
      loading.value = true;
      const data = await dispatchApi.del({ longs: ids.join() });
      if (data.code == 0) {
        messageC(data.msg, "success");
        getSearch();
      } else {
        alertC(data.msg, "warning");
      }
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  });
};

// 上报、审核、退回
const auditAbout = async (type: string): void => {
  loading.value = true;
  const auditParams: IAuditParams = {
    type: "official_doc_dispatch",
    selDatas: tabSelData.value,
  };
  try {
    const res = await useAuditAbout(type, auditParams);
    getSearch(1);
  } catch (error) {}
  loading.value = false;
};

// 归档
const collectSort = async (): void => {
  if (tabSelData.value.length != 1) {
    messageC("只能选择一条数据进行归档!");
    return;
  }

  if (tabSelData.value[0]["isFilter"] == 1) {
    messageC("请选择未归档的数据进行操作!");
    return;
  }
  await alertC("确认归档?", "confirm");
  loading.value = true;
  try {
    const res = await dispatchApi.updateIsFilter(tabSelData.value[0]["keyid"]);
    if (res.code == 0) {
      messageC(res.msg, "success");
      getSearch();
    } else {
      messageC(res.msg, "error");
    }
  } catch (error) {}
  loading.value = false;
};

defineExpose({
  toEdit,
});
</script>

<style lang="scss" scoped>
.icons-list :deep(.anticon) {
  margin-right: 6px;
  font-size: 24px;
}
</style>
